<?php

namespace app\logic\fp;

use app\common\enum\fp\PostLikeTypeEnum;
use app\common\model\fp\Post;
use app\common\model\fp\PostLike;
use app\logic\BaseLogic;
use think\facade\Db;

class PostLikeLogic extends BaseLogic
{
    /**
     * 点赞或者取消点赞
     * @param Post $post
     * @param $type
     * @param $userId
     * @return bool
     * @throws \Throwable
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function like(Post $post, $type, $userId): bool
    {
        $model = PostLike::initModel($post['id']);

        $find = $model->where(['user_id' => $userId, 'post_id' => $post['id']])->find();
        if ($find && PostLikeTypeEnum::from($type) === PostLikeTypeEnum::CANCEL) {
            $model->where(['user_id' => $userId, 'post_id' => $post['id']])->delete();
            $this->decLikeCount($post);
        }

        if (!$find && PostLikeTypeEnum::from($type) === PostLikeTypeEnum::LIKE) {
            $model->insert([
                'user_id' => $userId,
                'post_id' => $post['id'],
                'create_time' => time()
            ]);
            $this->incLikeCount($post);
        }
        return true;
    }

    /**
     * 获取点赞数量
     * @param $postId
     * @param $userId
     * @return mixed
     * @throws \Throwable
     */
    public  function getLikeCount($postId, $userId): mixed
    {
        $value = Post::initModel($userId)->where(['id' => $postId])->value('like_count');

        return $value ?: 0;
    }

    /**
     * 是否点赞
     * @param $postId
     * @param $userId
     * @return bool
     * @throws \Throwable
     */
    public function isLike($postId, $userId): bool
    {
        $count = PostLike::initModel($postId)->where(['user_id' => $userId, 'post_id' => $postId])->count();
        return $count > 0;
    }

    /**
     * 增加点赞数量
     * @throws \Throwable
     */
    public function incLikeCount(Post $post)
    {
        $table = Post::getDbTableName($post['user_id']);
        return Db::table($table)->where(['id' => $post['id']])->inc('like_count')->save();
    }

    /**
     * 增加点赞数量
     * @throws \Throwable
     */
    public function decLikeCount(Post $post)
    {
        $table = Post::getDbTableName($post['user_id']);
        return Db::table($table)->where(['id' => $post['id']])->dec('like_count')->save();
    }
}